package com.base.llpark.presenter;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.base.commonlib.base.presenter.BasePresenter;
import com.base.commonlib.bean.RoadEntity;
import com.base.commonlib.http.Api;
import com.base.commonlib.http.BaseResponse;
import com.base.commonlib.http.RealNetWorkUtil;
import com.base.commonlib.http.utils.CallBackImpl;
import com.base.commonlib.utils.BitmapUtil;
import com.base.commonlib.utils.MineRoadUtil;
import com.base.commonlib.utils.RetrofitUtils;
import com.base.llpark.bean.CarType;
import com.base.llpark.bean.LlPark;
import com.base.llpark.view.LlParkView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by weikailiang on 2019/9/19.
 */

public class LlParkPresenter extends BasePresenter<LlParkView> implements AMapLocationListener {

    public String[] mShengs = {"苏", "京", "津", "沪", "渝", "豫", "云", "辽", "黑", "浙", "皖", "湘", "赣", "新", "鄂", "贵", "甘", "晋", "蒙", "陕", "吉", "闽", "粤", "青", "藏", "川", "宁", "琼", "桂", "鲁", "冀"};
    public String[] mLetters = {"E", "B", "C", "D", "A", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    String pattern = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}(([A-HJ-Z]{1}[A-HJ-NP-Z0-9]{5})|([A-HJ-Z]{1}(([DF]{1}[A-HJ-NP-Z0-9]{1}[0-9]{4})|([0-9]{5}[DF]{1})))|([A-HJ-Z]{1}[A-D0-9]{1}[0-9]{3}警)))|([0-9]{6}使)|((([沪粤川云桂鄂陕蒙藏黑辽渝]{1}A)|鲁B|闽D|蒙E|蒙H)[0-9]{4}领)|(WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼·•]{1}[0-9]{4}[TDSHBXJ0-9]{1})|([VKHBSLJNGCE]{1}[A-DJ-PR-TVY]{1}[0-9]{5})";

    public List<RoadEntity> mRoadEntities;
    public List<RoadEntity> mMMineRoads;

    /**
     * 声明mlocationClient对象
     */
    private AMapLocationClient mLocationClient;
    /**
     * 声明mLocationOption对象
     */
    public AMapLocationClientOption mLocationOption = null;

    public LlParkPresenter(LlParkView view, Activity activity) {
        super(view, activity);
    }

    @Override
    public void start() {
        super.start();

        mMMineRoads = MineRoadUtil.getMineRoads(mUser.getUserId());
        mRoadEntities = MineRoadUtil.getRoads();

    }
    public int getRoadPosition(String street) {
        if (mRoadEntities != null) {
            for (int i = 0; i < mRoadEntities.size(); i++) {
                if (mRoadEntities.get(i).getRoadName().contains(street)) {
                    return i;
                }
            }
        }
        return -1;
    }


    public void initCraNo(String CarNo){
        mView.showPb();
        Map<String,String> map = new HashMap<>();
        map.put("carNo",CarNo);
        map.put("roadNo","");
        map.put("platform","android");
        Disposable enqueue = RealNetWorkUtil.postContent().method("api-ll/illegal/history")
                .content(map)
                .build().enqueue(String.class, new CallBackImpl<String>() {
                    @Override
                    public void onError(int code, String msg, String errMsg) {
                        mView.hidePb();
                        mView.showMes("该车辆违停次数查询错误");
                        getCarType();
                    }

                    @Override
                    public void onNext(String num) {
                       if (Integer.valueOf(num)>0){
                           mView.returnNotice(num);
                       }else {
                           getCarType();
                       }
                    }
                });
        mCompositeDisposable.add(enqueue);
    }

    private List<CarType> mCarTypes = null;
    public void getCarType(){
        mView.showPb();
        Disposable enqueue = RealNetWorkUtil.postContent().method("api-ll/dropdowm/selectCarKind").content(new Object())
                .build().enqueueForArray(CarType.class, new CallBackImpl<List<CarType>>() {
                    @Override
                    public void onError(int code, String msg, String errMsg) {
                        mView.hidePb();
                        mView.showMes("车辆类型查询错误");
                    }

                    @Override
                    public void onNext(List<CarType> carTypes) {
                        mView.hidePb();
                        mCarTypes = carTypes;
                        mView.returnSpinnerCarType(carTypes);
                    }
                });
        mCompositeDisposable.add(enqueue);
    }


    public void startLocationForLl(){
        mLocationClient = new AMapLocationClient(mActivity);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setHttpTimeOut(8000);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setLocationCacheEnable(true);
        // 设置定位监听
        mLocationClient.setLocationListener(this);
        // 设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        startMapLocation();
    }
    /**
     * 开启定位
     */
    public void startMapLocation() {
        //判断是否开启了，没有开启就开启
        if (!mLocationClient.isStarted()) {
            mLocationClient.startLocation();
        }
    }

    /**
     * 停止定位服务
     */
    public void stopMapLocation() {
        //判断服务是否开启了，若开启了则停止
        if (mLocationClient.isStarted()) {
            mLocationClient.stopLocation();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                // 可在其中解析amapLocation获取相应内容。
                //给接口设置数据
                if (TextUtils.isEmpty(aMapLocation.getAddress())||aMapLocation.getAddress() == null){
                    return;
                }
                mView.returnLocation(aMapLocation);
                stopMapLocation();
            } else {
                mView.showMes("定位权限未开启");
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                stopMapLocation();
            }
        } else {
            stopMapLocation();
        }
    }


    @Override
    public void release() {
        super.release();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    public void save(LlPark park){
        //压缩图片
        mView.showPb_mes("正在压缩图片。。。");
        List<String> paths = new ArrayList<>();
        for (int i=0;i<park.getFiles().size();i++){
            paths.add(BitmapUtil.compressImage(park.getFiles().get(i)));
        }
        //压缩完成
        mView.hidePb_mes();

        mView.showPb_mes("正在保存数据");
        Map<String, RequestBody> map = new LinkedHashMap<>();
        File file;
        for (int i=0;i<paths.size();i++){
            file = new File(paths.get(i));
            map.put("files"+"\";filename=\""+System.currentTimeMillis()+i+file.getName(),RequestBody.create(MediaType.parse("image/png"),file));
        }
        park.setCheckSignAddress(park.getCheckSignAddress().replace("_","-"));
        park.setCheckSignAddress(park.getCheckSignAddress().replace("#",""));
        map.put("carNo", RetrofitUtils.createPartFromString(park.getCarNo()));
        map.put("carType",RetrofitUtils.createPartFromString(park.getCarType()));
        map.put("checkDate",RetrofitUtils.createPartFromString(park.getCheckDate()));
        map.put("road",RetrofitUtils.createPartFromString(park.getRoad()));
        map.put("roadName",RetrofitUtils.createPartFromString(park.getRoadName()));
        map.put("checkSignAddress",RetrofitUtils.createPartFromString(park.getCheckSignAddress()));
        map.put("longitude",RetrofitUtils.createPartFromString(park.getLongitude()+""));
        map.put("latitude",RetrofitUtils.createPartFromString(park.getLatitude()+""));
        map.put("personId2",RetrofitUtils.createPartFromString(park.getPersonId2()));
        map.put("personName2",RetrofitUtils.createPartFromString(park.getPersonName2()));
        map.put("state",RetrofitUtils.createPartFromString(park.getState()));
        Api.getDefault(1).upllPark(map).enqueue(new Callback<BaseResponse<com.base.commonlib.bean.LlParkResult>>() {
            @Override
            public void onResponse(Call<BaseResponse<com.base.commonlib.bean.LlParkResult>> call, Response<BaseResponse<com.base.commonlib.bean.LlParkResult>> response) {
                mView.hidePb_mes();

                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (!TextUtils.isEmpty(response.body().getMsg())) {
                            mView.showMes("保存成功");
                        }
                        if (response.body().getStatus() == 1) {
                            mView.returnSaveSuccess(response.body().getData().getId(), response.body().getData().getObjType(),response.body().getData().getNoticeNO(),false);
                        } else {
                            mView.showMes(response.body().getMsg());
                        }
                    } else {
                        mView.showMes(response.body().getMsg());
                    }
                }else {
                    mView.showMes("未知错误");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<com.base.commonlib.bean.LlParkResult>> call, Throwable t) {
                mView.hidePb_mes();
                mView.showMes(t.toString());
            }
        });
    }
    public void updataPark(LlPark park, final boolean isUp){
        //压缩图片

        mView.showPb_mes("正在压缩图片。。。");
        List<String> paths = new ArrayList<>();
        for (int i=0;i<park.getFiles().size();i++){
            paths.add(BitmapUtil.compressImage(park.getFiles().get(i)));
//            paths.add(park.getFiles().get(i));
        }
        //压缩完成
        mView.hidePb_mes();

        mView.showPb_mes("正在保存数据");
        Map<String,RequestBody> map = new LinkedHashMap<>();
        File file;
        for (int i=0;i<paths.size();i++){
            file = new File(paths.get(i));
            map.put("files"+"\";filename=\""+System.currentTimeMillis()+i+file.getName(),RequestBody.create(MediaType.parse("image/png"),file));
        }
        park.setCheckSignAddress(park.getCheckSignAddress().replace("_","-"));
        park.setCheckSignAddress(park.getCheckSignAddress().replace("#",""));
        map.put("noticeNo",RetrofitUtils.createPartFromString(park.getNoticeNo()));
        map.put("id",RetrofitUtils.createPartFromString(park.getId()));
        map.put("carNo",RetrofitUtils.createPartFromString(park.getCarNo()));
        map.put("carType",RetrofitUtils.createPartFromString(park.getCarType()));
        map.put("checkDate",RetrofitUtils.createPartFromString(park.getCheckDate()));
        map.put("road",RetrofitUtils.createPartFromString(park.getRoad()));
        map.put("roadName",RetrofitUtils.createPartFromString(park.getRoadName()));
        map.put("checkSignAddress",RetrofitUtils.createPartFromString(park.getCheckSignAddress()));
        if (TextUtils.isEmpty(park.getLongitude())){
            map.put("longitude", RetrofitUtils.createPartFromString(""));
        }else {
            map.put("longitude", RetrofitUtils.createPartFromString(park.getLongitude() + ""));
        }
        if (TextUtils.isEmpty(park.getLatitude())){
            map.put("latitude", RetrofitUtils.createPartFromString(""));
        }else {
            map.put("latitude", RetrofitUtils.createPartFromString(park.getLatitude() + ""));
        }
        map.put("personId2",RetrofitUtils.createPartFromString(park.getPersonId2()));
        map.put("personName2",RetrofitUtils.createPartFromString(park.getPersonName2()));
        map.put("state",RetrofitUtils.createPartFromString(park.getState()));

        Api.getDefault(1).updataPark(map).enqueue(new Callback<BaseResponse<com.base.commonlib.bean.LlParkResult>>() {
            @Override
            public void onResponse(Call<BaseResponse<com.base.commonlib.bean.LlParkResult>> call, Response<BaseResponse<com.base.commonlib.bean.LlParkResult>> response) {
                mView.hidePb_mes();

                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (!TextUtils.isEmpty(response.body().getMsg())) {
                            if (!isUp){
                                mView.showMes("保存成功");
                            }

                        }
                        if (response.body().getStatus() == 1) {
                            mView.returnSaveSuccess(response.body().getData().getId(), response.body().getData().getObjType(), response.body().getData().getNoticeNO(),isUp);
                        } else {
                            mView.showMes(response.body().getMsg());
                        }
                    } else {
                        mView.showMes(response.message());
                    }
                }else {
                    mView.showMes("未知错误");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<com.base.commonlib.bean.LlParkResult>> call, Throwable t) {
                mView.hidePb_mes();
                mView.showMes(t.toString());
            }
        });


    }

    public int getTypePosition(String type) {
        if (mCarTypes != null) {
            for (int i = 0; i < mCarTypes.size(); i++) {
                if (mCarTypes.get(i).getDictValue().equals(type)) {
                    return i;
                }
            }
        }
        return 0;
    }

    public boolean checkPlateNumberFormat(String content) {
        return Pattern.matches(pattern, content);
    }
    public String getRoadId(String roadName){
        if (mRoadEntities != null){
            for (RoadEntity entity : mRoadEntities){
                if (!TextUtils.isEmpty(entity.getShowName())) {
                    if (entity.getShowName().equals(roadName)) {
                        return entity.getRoadNo();
                    }
                }
            }
        }
        return null;
    }



    //上报
    public void ReportLLpark(LlPark park){
        if (park.getState().equals("-1")){
            mView.showMes("请先保存");
            return;
        }
        mView.showPb();
        JSONObject jsobj = new JSONObject();
        try {
            jsobj.put("id",park.getId());
            jsobj.put("state",park.getState());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Api.getDefault(1).ReportLlPark(RetrofitUtils.createPartFromJson(jsobj.toString())).enqueue(new Callback<BaseResponse<String>>() {
            @Override
            public void onResponse(Call<BaseResponse<String>> call, Response<BaseResponse<String>> response) {
                mView.hidePb();
                if (response.body().getStatus()==1){
                    mView.showMes(response.body().getData());
                    mView.returnReportSuccess();
                }else{
                    mView.showMes(response.body().toString());
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<String>> call, Throwable t) {
                mView.hidePb();
                mView.showMes(t.toString());
            }
        });
    }
}
